package eran.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;

public final class FileUtils
{

    public static void writeStringToFile(String _str, String _filePath)
    {
        try
        {
            File f = new File(_filePath);
            if (f.exists())
            {
                f.delete();
            }
            f.createNewFile();
            OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(f, true), "UTF-8");
            ow.write(_str);
            ow.close();
            // BufferedWriter output = new BufferedWriter(new FileWriter(f));
            // output.write(_str);
            // output.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 读取后缀名
     */
    public static String getExtensionName(String filename)
    {
        if ((filename != null) && (filename.length() > 0))
        {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1)))
            {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 读取文件名
     */
    public static String getFileNameNoEx(String filename)
    {
        if ((filename != null) && (filename.length() > 0))
        {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length())))
            {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static String getFileMD5String(File file)
    {
        String md5Result = "notSet";
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream(file);
            md5Result = DigestUtils.md5Hex(fis);
            fis.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return md5Result;
    }
}
